package com.yupi.yuojbackendjudgeservice.judege;

import cn.hutool.json.JSONUtil;
import com.yupi.yuojbackendcommon.common.ErrorCode;
import com.yupi.yuojbackendcommon.exception.BusinessException;
import com.yupi.yuojbackendjudgeservice.judege.codesandbox.CodeSandbox;
import com.yupi.yuojbackendjudgeservice.judege.codesandbox.CodeSandboxFactory;
import com.yupi.yuojbackendjudgeservice.judege.strategy.DefaultJudgeStrategy;
import com.yupi.yuojbackendjudgeservice.judege.strategy.JavaLanguageJudgeStrategy;
import com.yupi.yuojbackendjudgeservice.judege.strategy.JudgeContext;
import com.yupi.yuojbackendjudgeservice.judege.strategy.JudgeStrategy;
import com.yupi.yuojbackendserviceclient.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import yuojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import yuojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import yuojbackendmodel.model.codesandbox.JudgeInfo;
import yuojbackendmodel.model.dto.question.JudgeCase;
import yuojbackendmodel.model.entity.Question;
import yuojbackendmodel.model.entity.QuestionSubmit;
import yuojbackendmodel.model.enums.QuestionSubmitStausEnum;
import yuojbackendmodel.model.enums.JudgeInfoMessageEnum;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 判题服务实现类
 * @Author JFeng
 * @Date 2023/10/15
 */
@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionFeignClient questionFeignClient;

    @Resource
    private JudgeManage judgeManage;

    @Value("${codesandbox.type}")
    private String type;

    /**
     * @see #doJudge(long)
     * @param questionSubmitId
     * @return
     */
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 获取题目提交信息
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        // 获得题目信息
        Question question = questionFeignClient.getQuestionById(questionSubmit.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目信息不存在");
        }
        // 判断题目是否为判题中
        if (!Objects.equals(questionSubmit.getStatus(), QuestionSubmitStausEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "正在判题中");
        }
        // 更改题目提交的状态
        QuestionSubmit updateSubmit = new QuestionSubmit();
        updateSubmit.setId(questionSubmitId);
        updateSubmit.setStatus(QuestionSubmitStausEnum.RUNNING.getValue());
        boolean success = questionFeignClient.updateQuestionSubmitById(updateSubmit);
        if (!success) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "判题状态更新错误");
        }
        // 调用代码沙箱
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        String judgeCaseStr = question.getJudgeCase();
        // 获取测试用例
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        // 判断输出用例和输入用例个数
        List<String> outputList = executeCodeResponse.getOutputList();
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeStrategy judgeStrategy = new DefaultJudgeStrategy();
        // 策略模式 模拟不同策略
        // 如果判断用那种策略比较复杂，定一个方法来判断策略
        if ("java".equals(language)){
            judgeStrategy = new JavaLanguageJudgeStrategy();
        }
        JudgeInfo judgeInfo = judgeManage.doJudge(judgeContext);
        // 修改数据库中的判题结果
        updateSubmit = new QuestionSubmit();
        updateSubmit.setId(questionSubmitId);
        updateSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        updateSubmit.setStatus(QuestionSubmitStausEnum.SUCCEED.getValue());
        success = questionFeignClient.updateQuestionSubmitById(updateSubmit);

        // 修改题目的提交数、通过数
        question.setSubmitNum(question.getSubmitNum() + 1);
        if (JudgeInfoMessageEnum.ACCEPTED.getValue().equals(judgeInfo.getMessage())) {
            question.setAcceptedNum(question.getAcceptedNum() + 1);
        }
        questionFeignClient.updateQuestionById(question);

        if (!success) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "判题状态更新错误");
        }
         // todo questionId
        return questionFeignClient.getQuestionSubmitById(questionSubmitId);
    }
}
